<template>
  <div>
    <div>
      <van-search
        v-model="input"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(input)"
      >
        <template #left>
          <div>{{location.district}}<i class="el-icon-location-information" @click="showAreaPopup"></i></div>
        </template>
        <template #action>
          <div  class ="span2" v-if="name !== ''">
            <el-dropdown>
            <span class="el-dropdown-link">
              {{name}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item divided @click.native="logout">
                  <span style="display:block;">退出</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div v-else>
            <router-link  to="/app/user/login" class ="span2">登录</router-link>
          </div>
        </template>
      </van-search>

      <van-popup v-model="areaShow" @close="onAreaClose" class="selectArea">
        <van-area :area-list="this.areaList" @confirm="areaConfirm" @cancel="areaCancel"/>
      </van-popup>
    </div>
    <div class="category">
        <van-swipe class="my-swipe"  indicator-color="green">
          <van-swipe-item v-for="row in listTemp">
            <el-row>
              <el-col :span="6" v-for="item in row">
                <div class="block" @click="onSearch(input,item.id)">
                  <el-avatar class="category-img" shape="square" :size="50" :src="item.iconUrl" :key="item.iconUrl"></el-avatar>
                  <p>{{item.name}}</p>
                </div>
              </el-col>
            </el-row>
          </van-swipe-item>
        </van-swipe>
    </div>

    <div>
      <van-tabs sticky swipeable active="a" @click="onTabsClick">
        <van-tab title="猜你喜欢" name="a">
          <van-list
            v-model="goodsLoading"
            :finished="goodsFinished"
            @load="onGoodsLoad"
            :offset="10"
            finished-text="没有更多了"
            :immediate-check="false"
          >
            <div v-for="item in goodsList">
              <van-card
              :desc="item.description"
              :title="item.goodName"
              :thumb="item.iconUrl"
              @click="toGoodsDetail(item.id)"
            >
              <div slot="price" class="price">
                <span class="shopRemarkScore">￥{{item.price}}</span>
              </div>
              <div slot="footer">

              </div>
            </van-card>
            </div>
          </van-list>
        </van-tab>
        <van-tab title="发现好店" name="b">
          <van-list
            v-model="loading"
            :finished="finished"
            @load="onLoad"
            :offset="10"
            finished-text="没有更多了"
            :immediate-check="false"
          >
            <div v-for="item in shopList">
              <van-card
                :desc="item.introduction"
                :title="item.name"
                :thumb="item.iconUrl"
              >
                <div slot="tags">
                  <p>{{item.tags}}</p>
                </div>
                <div slot="price" class="price">
                  <van-rate :value="item.remarkScore" size="10" readonly />
                  <span class="shopRemarkScore">{{item.remarkScore}}</span>
                  <span class="shopPersonPrice">{{item.pricePerMan}}/人</span>
                </div>
                <div slot="bottom">
                  <p>{{item.address}}<span class="distance">{{item.distance}}</span></p>
                </div>
                <div slot="footer">
                  <van-button plain size="mini" type="primary" @click="toShopIndex(item.id)">进店</van-button>
                </div>
              </van-card>
            </div>
          </van-list>
        </van-tab>
      </van-tabs>
    </div>
    <div>
      <index-footer></index-footer>
    </div>
  </div>


</template>

<script>
    import { mapGetters } from 'vuex'
    import { list } from '@/api/category'
    import { getUrl } from  '@/api/file'
    import { searchEs ,searchGoods,updateUserShopScore} from "@/api/search";
    import { recommendShop ,recommendGoods} from  "@/api/recommend"
    import { Toast } from 'vant';
    import IndexFooter from "@/views/app/components/footer";
    import loadBMap from "@/utils/loadBMap";
    import areaList from  "@/assets/js/area";
    import {kmFormat,mFormat} from "@/utils/distance";
    // import 'mint-ui/lib/style.css'
    export default {
      name: "index",
      components: {IndexFooter},
      computed: {
        ...mapGetters([
          'name'
        ]),
        listTemp: function () {
          var list = this.categoryList;
          var arrTemp = [];
          var index = 0;
          var sectionCount = 8;
          for (var i = 0; i < list.length; i++) {
            index = parseInt(i / sectionCount);
            if (arrTemp.length <= index) {
              arrTemp.push([]);
            }
            arrTemp[index].push(list[i]);
          }
          return arrTemp;
        }

      },
      props:['idx'],
      methods: {
        async logout() {
          await this.$store.dispatch('user/logout');
          this.$router.push(`/app/index`)
        },
        onSearch: function (input,category) {
          this.$router.push({
            name: 'SearchIndexRouter',
            query: {
              input: input,
              selectCategory: category
            }
          });
        },
        toShopIndex: function (shopId) {
          this.$router.push({
            name: 'Shop',
            query: {
              shopId: shopId,
            }
          });
        },
        updateAddress(){
          console.log("重新选择位置")
        },
        onTabsClick(name, title) {
          Toast(title);
        },// 浏览器定位函数
        async geolocation() {
          await loadBMap('4c4WdyR21Q9IsGNwqVqynxK4dXQEiHSK');
          let that = this;
          let geolocation = new BMap.Geolocation();
          if(!sessionStorage.getItem('location')){
            geolocation.getCurrentPosition(function(res) {
                if (this.getStatus() === BMAP_STATUS_SUCCESS) {
                  let bMapPosition = res;
                  console.log(bMapPosition);
                  //存储
                  that.location.province = bMapPosition.address.province;
                  that.location.city = bMapPosition.address.city;
                  that.location.district = bMapPosition.address.district;
                  that.location.longitude = bMapPosition.longitude;
                  that.location.latitude = bMapPosition.latitude;
                  sessionStorage.setItem('location', JSON.stringify(that.location));
                  // 调用推荐接口
                } else {
                  Toast("无法获取当前位置!");
                  that.location.district = "定位失败";
                }
            }, { enableHighAccuracy: true })
          }
        },
        showAreaPopup() {
          this.areaShow= true;
        },
        onAreaClose() {
          this.areaShow= false;
        },
        areaConfirm(objects){
          let selectAddress="";
          objects.forEach(item=>{
            selectAddress+=item.name;
          })
          // 调用百度地图并存储
          this.$jsonp('http://api.map.baidu.com/geocoding/v3/', {
            address: selectAddress,
            output: 'json',
            ak: 'Iavfm6ydXMsSi7xPMIDlsSSGfSGRZdkW'
          }).then(json => {
            // 得到我们想要的内容
            console.log(json)
            //存储
            this.location.province =objects[0].name;
            this.location.city = objects[1].name;
            this.location.district = objects[2].name;
            this.location.longitude = json.result.location.lng;
            this.location.latitude = json.result.location.lat;
            // 门店
            this.searchPage.longitude = json.result.location.lng;
            this.searchPage.latitude = json.result.location.lat;
            // 商品
            this.searchGoodsPage.longitude = json.result.location.lng;
            this.searchGoodsPage.latitude = json.result.location.lat;
            sessionStorage.setItem('location', JSON.stringify(this.location));
            this.areaShow= false;
            this.address = this.location.district;
            // 刷新推荐
            this.initPageAndGetShopList();
          }).catch(err => {
            console.log(err)
          })
        },
        areaCancel(){
          this.areaShow= false;
        },
        initPageAndGetShopList(){
          this.searchPage.page = 1;
          this.shopList = [];
          this.searchGoodsPage.page = 1;
          this.goodsList = [];
          // 同步调用，加载之后才设置分页没有结束
          this.getShopList();
          this.finished = false;
          this.getGoodsList();
          this.goodsFinished = false;
        },
        getGoodsList(){
          recommendGoods(this.searchGoodsPage).then((response) => {
            let pageBean = response.data;
            if(pageBean.pageList.length===0){
              this.goodsFinished = true;
              return;
            }
            pageBean.pageList.forEach(goods=>{
              // 距离计算
              // goods.distance=kmFormat(goods.distance);
              // 图片加载
              getUrl(goods.iconUrl).then((response) => {
                goods.iconUrl = response.data;
              })
            });
            this.goodsList=this.goodsList.concat(pageBean.pageList);
            this.goodsTotalCount = pageBean.goodsTotalCount;
            this.goodsLoading = false;
          }).catch((response) => {
            console.log(response);
          });
        },
        getShopList(){
          recommendShop(this.searchPage).then((response) => {
            let pageBean = response.data;
            if(pageBean.pageList.length===0){
              this.finished = true;
              return;
            }
            pageBean.pageList.forEach(shop=>{
              // 距离计算
              // shop.distance=kmFormat(shop.distance);
              // shop.distance = this.locationIndex(shop);
              // 图片加载
              getUrl(shop.iconUrl).then((response) => {
                shop.iconUrl = response.data;
              })
            });
            this.shopList=this.shopList.concat(pageBean.pageList);
            this.totalCount = pageBean.totalCount;
            this.loading = false;
          }).catch((response) => {
            console.log(response);
          });
        },
        onLoad(){
          console.log("加载。。。")
          this.searchPage.page++;
          this.getShopList();
        },
        onGoodsLoad(){
          this.searchGoodsPage.page++;
          this.getGoodsList();
        },
        toGoodsDetail(id){
          this.$router.push({
            name: 'Goods',
            query: {
              goodsId: id,
            }
          });
        },
        locationIndex(shopVo){
            this.location =JSON.parse(sessionStorage.getItem('location'));

            let map = new BMap.Map("container");
            let point1 = new BMap.Point(this.location.longitude,this.location.latitude);
            let point2 = new BMap.Point(shopVo.longitude,shopVo.latitude);
            let distance = map.getDistance(point1,point2);
            return mFormat(distance);
        },

      },
      mounted() {
        //加载品类
        list().then((response) => {
          this.categoryList= response.data;
          //加载图片
          this.categoryList.forEach(category=>{
            getUrl(category.iconUrl).then((response) => {
              category.iconUrl = response.data;
            })
          })

        }).catch((response) => {
          console.log(response);
        });
        if (sessionStorage.getItem('location')){
          this.location =JSON.parse(sessionStorage.getItem('location'));
        }
        //异步加载地图
        this.geolocation();

      },
      watch:{
        location(val){
          this.searchPage.longitude=val.longitude;
          this.searchPage.latitude=val.latitude;
          this.searchGoodsPage.longitude=val.longitude;
          this.searchGoodsPage.latitude=val.latitude;
          this.getShopList();
          this.getGoodsList();
        }
      },
      data() {
          return {
            input: '',
            select: '',
            categoryList:[],
            categoryGroupList:[],
            areaShow:false,
            selectLocation:false,
            areaList,
            location:{
              province:"",
              city:"",
              district:"位置",
              longitude:"",
              latitude:"",
            },
            searchPage:{
              page: 1,
              size: 5,
              longitude:"",
              latitude:"",
            },
            searchGoodsPage:{
              page: 1,
              size: 5,
              longitude:"",
              latitude:""
            },
            shopList:[],
            goodsList:[],
            totalCount:0,
            goodsTotalCount:0,
            loading: false,
            goodsLoading: false,
            finished: false,
            goodsFinished: false,
          }
        }
    }
</script>

<style scoped>
  .indexHead{
    background-color: rgb(47,149,204);
    height: 36px;
  }
  .indexHead .span1{
    height: 100%;
    line-height:36px;
    float: left;
    margin-left: 10px;
  }
  .indexHead .span2{
    height: 100%;
    line-height:36px;
    float: right;
    margin-right: 10px;
  }
  .selectArea{
    width: 100%;
  }
  /*分类*/
  .category{
    height: 200px;
  }
  .block{
    text-align: center;
  }
  .block .category-img{
    margin-top: 10px;
    background-color: white;
  }
  .block p{
    font-size: 12px;
    margin-top: 2px;
  }
  .category-img{

  }
  .category-img img{
    width: 100%;
  }

  /**商品**/
  .shopRemarkScore{
    color: brown;
    margin-left: 5px;
  }
  .shopPersonPrice{
    margin-left: 10px;
  }
  .distance{
    float: right;
  }
</style>
